package com.iflytek.http.impl;

import java.lang.ref.WeakReference;
import java.util.LinkedList;
import java.util.Queue;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;

public class HttpOperationUtil {
	private static final String TAG = HttpOperationUtil.class.getSimpleName();

	private Context mContext;

	Handler mHandler = new Handler();
	private WeakReference<HttpOperationService> mService;
	private Queue<AbstractOperation> mRequests = new LinkedList();
	protected Class<? extends HttpOperationService> mServiceClz;


	public HttpOperationUtil(Context context){
		mContext = context;
		if (null == mContext){
			throw new NullPointerException();
		}
	}

	public void setOperationService(Class<? extends HttpOperationService> clz){
		mServiceClz = clz;
	}

	public void stopAfterDone() {
		if (isServiceAvailable()){
			((HttpOperationService)mService.get()).stopAfterDone();
		}
	}

	public void stopServiceNow(){
		if (isServiceAvailable()){
			((HttpOperationService)mService.get()).stopServicNow();
		}
	}

	public void request(AbstractOperation request){
		mRequests.add(request);
		handleRequests();
	}

	private void handleRequests(){
		if (isServiceAvailable()){
			dispatchOperations();
		}else{
			mContext.startService(new Intent(mContext, mServiceClz));
		}
	}

	private void dispatchOperations(){
		while (mRequests.peek() != null) {
			AbstractOperation operationRequest = (AbstractOperation)mRequests.remove();
			((HttpOperationService)mService.get()).doRequest(operationRequest);
		}
	}

	void onServiceStarted(HttpOperationService service){
		mService = new WeakReference<HttpOperationService>(service);
		handleRequests();
	}
	
	/**
	 * 服务是否可用
	 * @return
	 */
	private boolean isServiceAvailable(){
		return (mService != null) && (mService.get() != null);
	}
}
